package com.netwit.shiro.jwt;

import com.netwit.shiro.jwt.util.JWTUtil;
import com.netwit.shiro.jwt.util.PasswordHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Slf4j
@Service
public class JWTRealm extends AuthorizingRealm {

    @Autowired
    private PasswordHelper passwordHelper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userId = JWTUtil.getUserId(principalCollection.toString());
        Map<String, Object> user = passwordHelper.getUser(userId);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token  = (String) authenticationToken.getCredentials();
        String userId = JWTUtil.getUserId(token);
        if (StringUtils.isEmpty(userId)) {
            throw new AuthenticationException("token invalid");
        }
        Map<String, Object> user = passwordHelper.getUser(userId);
        if (user == null) {
            throw new AuthenticationException("User doesn't exists");
        }
        if (!JWTUtil.verify(token, userId, (String) user.get("password")).equals("success")) {
            throw new AuthenticationException("User's name or password is invalid");
        }
        return new SimpleAuthenticationInfo(token, token, "jwt_realm");
    }
}
